package com.utility.seralize;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * 序列化类
 */
public class SerializeUtility {
	/**
	 * 将对象转成字节数组
	 * @param object
	 * 		需要序列化的对象
	 * @return
	 * @throws IOException 
	 */
	public static byte[] serialize(Object object) throws IOException{
		if(object == null){
			return null;
		}
		ObjectOutputStream objectOutputStream = null;
        ByteArrayOutputStream byteArrayOutputStream = null;
        byteArrayOutputStream = new ByteArrayOutputStream();
    	objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
    	objectOutputStream.writeObject(object);
        return byteArrayOutputStream.toByteArray();
	}
	
	/**
	 * 反序列化
	 * @param bytes
	 * 		对象字节数组
	 * @return
	 * @throws IOException 
	 * @throws ClassNotFoundException 
	 */
	@SuppressWarnings("unchecked")
	public static <T> T unserialize(byte[] bytes) throws IOException, ClassNotFoundException{
		ByteArrayInputStream byteArrayInputStream = null;
		byteArrayInputStream = new ByteArrayInputStream(bytes);
        ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
        return (T)objectInputStream.readObject();
	}
}
